package com.bw.home.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bw.home.R
import com.bw.home.entity.VideoTypeEntityItem

class VideoTypeAdapter : RecyclerView.Adapter<VideoTypeAdapter.VideoTypeViewHolder>() {

    private var videoTypeList: List<VideoTypeEntityItem> = emptyList()
    private var onItemClickListener: ((VideoTypeEntityItem) -> Unit)? = null
    private var selectedPosition = 0
    // 获取当前列表（方便Fragment查找位置）
    fun currentList() = videoTypeList
    fun setData(list: List<VideoTypeEntityItem>) {
        this.videoTypeList = list
        notifyDataSetChanged()
    }

    fun setOnItemClickListener(listener: (VideoTypeEntityItem) -> Unit) {
        this.onItemClickListener = listener
    }

    fun setSelectedPosition(position: Int) {
        val oldPosition = selectedPosition
        selectedPosition = position
        // 只有位置变化时才刷新
        if (oldPosition != position) {
            notifyItemChanged(oldPosition)
            notifyItemChanged(selectedPosition)
        }


    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VideoTypeViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.home_top_main, parent, false)
        return VideoTypeViewHolder(view)
    }

    override fun onBindViewHolder(holder: VideoTypeViewHolder, position: Int) {
        holder.bind(videoTypeList[position], position == selectedPosition)
    }

    override fun getItemCount(): Int = videoTypeList.size

    inner class VideoTypeViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val textView: TextView = itemView.findViewById(R.id.home_top)

        fun bind(item: VideoTypeEntityItem, isSelected: Boolean) {
            textView.text = item.typename
            
            // 设置选中状态样式
            if (isSelected) {
                textView.setTextColor(itemView.context.getColor(android.R.color.holo_red_dark))
                textView.textSize = 16f
            } else {
                textView.setTextColor(itemView.context.getColor(android.R.color.black))
                textView.textSize = 14f
            }

            itemView.setOnClickListener {
                onItemClickListener?.invoke(item)
                setSelectedPosition(adapterPosition)
            }
        }
    }
}